package com.demo.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigLoader {
    private static Properties properties;
    public static final File configDir = new File("config");
    public static final File configFile = new File(configDir, "smtp.properties");

    static {
        loadConfig();
    }

    public static String getProperty(String key) {
        return properties.getProperty(key);
    }

    public static Properties getMailProperties() {
        Properties mailProps = new Properties();
        // 筛选出所有mail.smtp开头的配置项
        properties.stringPropertyNames().stream()
                .filter(key -> key.startsWith("mail"))
                .forEach(key -> mailProps.setProperty(key, properties.getProperty(key)));
        return mailProps;
    }

    public static void loadConfig() {
        System.out.println("初始化：读取配置文件");
        properties = new Properties();
        try (InputStream input = new FileInputStream(configFile)) {
            if (!configFile.exists()) {
                throw new RuntimeException("无法找到配置文件: " + configFile);
            }
            properties.load(input);
        } catch (IOException e) {
            throw new RuntimeException("加载配置文件失败", e);
        }
        System.out.println("初始化：读取配置文件结束");
    }
}